package com.zhihuishu.treenity.service.operation.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.able.commons.dto.BaseVideoDto;
import com.able.commons.httpinvoker.IFileCommonsInvoker;
import com.able.livecourse.rmi.dto.ResponseModule;
import com.able.livecourse.rmi.service.LiveCourseRmiService;
import com.able.openapi.overseas.IOnlineSchoolForOverseasService;
import com.able.openapi.overseas.dto.RecruitStudyInfoTreenityDto;
import com.able.openapi.overseas.dto.TeachingTaskDto;
import com.able.openapi.overseas.dto.TreenityPostActiveNumDto;
import com.able.openapi.overseas.dto.TreenityStuActiveNumDto;
import com.zhihuishu.toolkit.log.LoggerTemplate;
import com.zhihuishu.toolkit.log.MDCInfoBuilder;
import com.zhihuishu.treenity.consts.Constants;
import com.zhihuishu.treenity.dto.StuActiveNumDto;
import com.zhihuishu.treenity.dto.VideoinfoDto;
import com.zhihuishu.treenity.service.operation.RunhomeService;
import com.zhihuishu.treenity.util.CopyObjUtils;
import com.zhihuishu.user.openapi.common.UserQueryOpenService;
import com.zhihuishu.user.openapi.common.dto.UserOpenDto;
import com.zhihuishu.user.openapi.wrapper.ResultWrapper;



@Service("runhomeService")
public class RunhomeServiceImpl implements RunhomeService {
	protected LoggerTemplate log = LoggerTemplate.getInstance(this.getClass());
	@Resource
	private LiveCourseRmiService treenityLiveCourseRmiService;
	@Resource
	private IFileCommonsInvoker iFileCommonsInvoker;
	@Resource
	private UserQueryOpenService userQueryOpenService;
	@Resource
	public IOnlineSchoolForOverseasService iOnlineSchoolForOverseasService;
	@Override
	public RecruitStudyInfoTreenityDto findRecruitStudyInfo(Integer recruitId) {
		RecruitStudyInfoTreenityDto recruitStudyInfoTreenityDto=new RecruitStudyInfoTreenityDto();
		try {
			recruitStudyInfoTreenityDto=iOnlineSchoolForOverseasService.findRecruitStudyInfo(recruitId);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return recruitStudyInfoTreenityDto;
	}

	@Override
	public List<VideoinfoDto> findTeachingTaskList(Integer recruitId) {
		List<VideoinfoDto> videoinfoDtos=new  ArrayList<VideoinfoDto>();
		List<TeachingTaskDto> teachingTaskDtos=new ArrayList<TeachingTaskDto>();
		try {
			teachingTaskDtos=iOnlineSchoolForOverseasService.findTeachingTaskList(recruitId);
			if(teachingTaskDtos!=null){
				String ids="";
				for(int i = 0; i < teachingTaskDtos.size(); i++){
					if(teachingTaskDtos.get(i).getVideoId()!=null){
					ids+=teachingTaskDtos.get(i).getVideoId()+(teachingTaskDtos.size()==i+1?"":",");
					}
					VideoinfoDto videoinfoDto=new VideoinfoDto();
					CopyObjUtils.copyObj(videoinfoDto, teachingTaskDtos.get(i));
					videoinfoDtos.add(videoinfoDto);
					
				}
				if(!ids.equals("")){
					//获取视频信息
				List<BaseVideoDto> baseVideoDtos=iFileCommonsInvoker.findVideoByIds(ids);
				for (int i = 0; i < baseVideoDtos.size(); i++) {
					for (int j = 0; j < videoinfoDtos.size(); j++) {
					if(baseVideoDtos.get(i).getId().equals(videoinfoDtos.get(j).getVideoId())){
						videoinfoDtos.get(j).setVideoTime(baseVideoDtos.get(i).getDuration()+"");
						videoinfoDtos.get(j).setCoverPicture(baseVideoDtos.get(i).getThumbnailPath());
					}
				  }
				}
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return videoinfoDtos;
	}


	@Override
	public Map<Object, Object> findforum(Integer recruitId) {
		Map<Object, Object> map = new HashMap<Object, Object>();
			List<Long> ids=new ArrayList<Long>();
			try {	List<StuActiveNumDto> stuActiveNumDtos=new ArrayList<StuActiveNumDto>();
			//获取热帖
			List<TreenityPostActiveNumDto> treenityPostActiveNumDtos=iOnlineSchoolForOverseasService.findbyRecruitId(recruitId);
			//活跃人数
			Integer countForum =iOnlineSchoolForOverseasService.findByRecruitIdAndDate(recruitId);
			//活跃学生
			List<TreenityStuActiveNumDto> treenityStuActiveNumDtos=iOnlineSchoolForOverseasService.findByRecruitId(recruitId);
			if(treenityStuActiveNumDtos!=null &&!treenityStuActiveNumDtos.isEmpty()){
				for (int i = 0; i < treenityStuActiveNumDtos.size(); i++) {
					StuActiveNumDto stuActiveNumDto=new StuActiveNumDto();
					CopyObjUtils.copyObj(stuActiveNumDto, treenityStuActiveNumDtos.get(i));
					stuActiveNumDtos.add(stuActiveNumDto);
					ids.add(Long.parseLong(treenityStuActiveNumDtos.get(i).getUserId().toString()));
				}
				if(!ids.isEmpty()){
				ResultWrapper<List<UserOpenDto>> list = userQueryOpenService.list(ids);
				for (UserOpenDto userOpenDto : list.getResult()) {
					for (StuActiveNumDto stuActiveNumDto : stuActiveNumDtos) {
						if(Long.parseLong(stuActiveNumDto.getUserId().toString())==userOpenDto.getUserId())
						{
					String avatar="";
					// 完善用户头像
			    	if(StringUtils.isBlank(userOpenDto.getAvatar())) {
			    		// 为空是，填充默认用户头像
			    		avatar=Constants.FTP_URL_SUFFIX_IMG + Constants.USER_AVATAR_IMG_PATH;
			    	} else if(!StringUtils.startsWithIgnoreCase(userOpenDto.getAvatar(), "http")) {
			    		// 非以http开头时，添加前缀
			    		avatar=Constants.FTP_URL_SUFFIX_IMG + userOpenDto.getAvatar();
			    	}else{
			    		avatar=userOpenDto.getAvatar();
			    	}
			    	//对用户头像进行进一步操作，获取最小的图片
			    	avatar = avatar.substring(0,avatar.lastIndexOf("."))+Constants.FTP_URL_POSTFIX_S3_IMG+avatar.substring(avatar.lastIndexOf("."));
			    	stuActiveNumDto.setImgurl(avatar);
			    	stuActiveNumDto.setRealname(userOpenDto.getRealname());
					}
					}
				}
				}
				}
				map.put("treenityPostActiveNumDtos", treenityPostActiveNumDtos);
				map.put("countForum", countForum);
				map.put("stuActiveNumDtos", stuActiveNumDtos);
		} catch (NumberFormatException e) {
			log.error(e.getMessage());
		}
		return map;
	}

	@Override
	public Map<String, Object> runExe(int liveCourseId, int type,Long userId) {
		Map<String,Object> zoomInfo=null;
    	int meetingCount = 0;
		if(0!=liveCourseId){
			MDCInfoBuilder builder = MDCInfoBuilder.create()
					.setModuleName("TeachingTaskService_loadZoom")
					.setTableName("JMK");
			try{
				ResponseModule responseModule = treenityLiveCourseRmiService.findVirtualStartUrlBycourseId(liveCourseId);
				//type 1表示PC  2表示APP
				ResponseModule responseModuleJoin = treenityLiveCourseRmiService.joinVirtualCourseRecordUser(userId, liveCourseId, 1);
				//获取当前会议人数
				if (responseModuleJoin!=null) {
					if ("0000".equals(responseModuleJoin.getRspCode())) {
						@SuppressWarnings("unchecked")
						Map<String,String> map= (Map<String, String>) responseModuleJoin.getRspData();
						if(map!=null){
							String currentCount = map.get("currentCount");
							if(currentCount!=null){
								meetingCount = Integer.parseInt(currentCount);
							}
						}
					}
				}
				if (responseModule!=null) {
					if ("0000".equals(responseModule.getRspCode())) {
						@SuppressWarnings("unchecked")
						Map<String,String> map= (Map<String, String>) responseModule.getRspData();
						String url="";
						if(null!=map){
							zoomInfo=new HashMap<String,Object>();
							String meetingId = map.get("meetingId");
							String startUrl = map.get("startUrl");
							if(null!=startUrl&&!"".equals(startUrl)){
								if(type==1){//学生或者助教
									url="http://lc.zhihuishu.com/live/live_room.html?liveId="+liveCourseId;
									builder.put("message1", "UserId="+userId+"非核心调用----liveCourseId="+url);
								}
							}
							if(null!=startUrl&&!"".equals(startUrl)){
								if(type==2){//直播老师
									//判断人数是否超过200，没有进入瞩目直播，超过进入智慧树直播
									if(meetingCount<200){
										url=startUrl;
										builder.put("message2", "UserId="+userId+"调用瞩目会议室成功----ZoomUrl="+url);
									}else{										
										url="http://lc.zhihuishu.com/live/live_room.html?liveId="+liveCourseId;
										builder.put("message3", "UserId="+userId+"调用瞩目会议室成功--人数超过200--ZoomUrl="+url);
									}
									
								}
							}
							zoomInfo.put("url", url);
							zoomInfo.put("zoomId", meetingId);
							zoomInfo.put("hostId", userId);
						}
					}				
				}
				log.warn(builder.build(),"call loadZoom success");
			}catch(Exception e){
				log.error(builder.build(),"UserId="+userId+"调用瞩目会议室失败----ZoomUrl=",e);
			}
		}
		return zoomInfo;
	}

}
